#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import scrapy
import json
import math
import time
import urllib.parse

from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class XinjiangAksdqPolicy(BaseTaxPolicySpider):
    name = 'xinjiang_aksdq_policy'
    
    province = '新疆维吾尔自治区'
    city: str = "阿克苏地区"  # 取表格
    # county: str = ""  # 取表格
    park: str = ""  # 取表格

    def start_requests(self):
        for source, county, url in [
            ['新疆维吾尔自治区阿克苏地区人民政府', "", "https://www.aks.gov.cn/zwgk/fgwj/zfwj/xzgfxwj/index.html"],
            ['新疆维吾尔自治区阿克苏地区人民政府', "", "https://www.aks.gov.cn/zwgk/fgwj/zfwj/gj/index.html"],
            ['阿克苏市人民政府', "阿克苏市", "https://www.akss.gov.cn/zwgk/fgwj/xzgfxwj/index.html"],
            ['库车市人民政府', "库车市", "https://www.xjkc.gov.cn/zwgk/fgwj/zfwj/index.html"],
            ['库车市人民政府', "库车市", "https://www.xjkc.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['沙雅县人民政府', "沙雅县", "https://www.xjsy.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['沙雅县人民政府', "沙雅县", "https://www.xjsy.gov.cn/zwgk/fgwj/zfwj/index.html"],
            ['新和县人民政府', "新和县", "https://www.xjxinhe.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['新和县人民政府', "新和县", "https://www.xjxinhe.gov.cn/zwgk/fgwj/zfwj/index.html"],
            ['拜城县人民政府', "拜城县", "https://www.xjbc.gov.cn/zwgkml/zfwj/gfxwj/index.html"],
            ['温宿县人民政府', "温宿县", "https://www.wszf.gov.cn/zwgk/fgwj/zcfg/index.html"],
            ['温宿县人民政府', "温宿县", "https://www.wszf.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['阿瓦提县人民政府', "阿瓦提县", "https://www.xjawt.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['乌什县人民政府', "乌什县", "https://www.ws.gov.cn/zwgk/fgwj/gfxwj/index.html"],
            ['乌什县人民政府', "乌什县", "https://www.ws.gov.cn/zwgk/fgwj/zfwj/index.html"],
            ['柯坪县人民政府', "柯坪县", "https://www.xjkpx.gov.cn/zwgk/fgwj/gfxwj/index.html"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item})

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(""".""").re(r'"url"\:\s*"(http.*?)"')
        print(response.url, len(elem_list))
        for elem in elem_list[:1]:
            item = Item()
            item['source_url'] = elem
            item['source_url'] = response.urljoin(item['source_url'])
            # item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
                continue
            print(response.url, item['source_url'])
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item})
        if response.meta.get("is_next") is not False:
            pages = response.xpath("//script").re_first(r"""createPageHTML\('page_?-?div',(\d+),""") or 0
            print(response.url, f"page: {pages}")
            for page_num in range(2, int(pages) + 1):
                url = response.url.replace(".shtml", f"_{page_num}.shtml")
                yield response.follow(url, callback=self.parse_list, meta={'item': prev_item, 'is_next': False})

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("""string(//meta[@name='PubDate']/@content)""").get() or response.xpath("//*[@class='fbrq']/text()").get()
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl xinjiang_aksdq_policy".split())
